/*
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Authors:
 *  	Albert Marieges Garcia
 *  	Álex Pardo Fernández
 *  	Enric Mayas Márquez
 *  	Juan Carlos Calvo Tejedor
 *  	Marc Gironés Dezsényi
 *  
 *  Contact:
 *  	bcn.tours.android@gmail.com
 *  Webpage:
 *  	bcntours.co.cc
 *
 */
package com.BCNTours.Vista;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;

import com.BCNTours.R;
import com.BCNTours.AR.Vista.ARactivity;
import com.BCNTours.Maps.Vista.MapMode;
import com.BCNTours.Model.ApplicationData;

/**
 * Main class of the application that displays the main menu.
 *
 */
public class BCNTours extends Activity {    
    
	/*Attributions*/
    private ApplicationData applicationData;
    @SuppressWarnings("unused")
	private int lang;
    static public ProgressDialog loading;
    
    
    /** 
     * Called when the activity is first created. 
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        setWindowOptions();
        //Retrieve extended data from the intent
        Bundle extra = getIntent().getExtras();
        applicationData = (ApplicationData) extra.get("database");
        lang = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getInt(Preferences.PREF_LANG, 3);
        
        setContentView(R.layout.main);  
    }
    
    /**
     * BtnActionListener of the main menu
     */
    public void btnMainMenuActionPerformed(View view){
    	Intent intent = new Intent();
    	String msg;
    	switch(view.getId()){
    	
	    	//Button POIs
			case R.id.btnMenuPoi:
				intent = new Intent(BCNTours.this, Categories.class);
				intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
				startActivity(intent);
				break;

			//Button Camera
			case R.id.btnMenuMap:
				msg = getString(R.string.msgloading);
				loading = ProgressDialog.show(BCNTours.this, "", 
		                msg, true);
				intent = new Intent(BCNTours.this, MapMode.class);
				intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
				startActivity(intent);
				break;
				
			//Button Map
			case R.id.btnMenuCamera:
				//Only if location service is available would start the activity
				if(isLocationAvailable()){  
					msg = getString(R.string.msgloading);
					loading = ProgressDialog.show(BCNTours.this, "", 
			                msg, true);
					
					intent = new Intent(BCNTours.this, ARactivity.class);
					intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
					BCNTours.this.startActivityForResult(intent, 2);
				}
				break;

			//Button preferences
			case R.id.btnMenuPreferences:
				intent = new Intent(BCNTours.this, Preferences.class);
				intent.putExtra("com.ShowMe.Model.PoiList", applicationData);
				BCNTours.this.startActivityForResult(intent, 1);
				break;		
		}
    }


	/**
	 * Action listener of the back button
	 */
	@Override
	public void onBackPressed() {
		//Create the exit dialog 
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		//Set the message of the dialog
		builder.setMessage(R.string.msgExit)
		       .setCancelable(false)
		       .setPositiveButton(R.string.msgYes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                BCNTours.this.finish();
		           }
		       })
		       .setNegativeButton(R.string.msgNo, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
		
		//Create and show the exit dialog
		builder.create();
		builder.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == 0){
			BCNTours.this.finish();
		}
		if(requestCode == 1){
			
			applicationData = (ApplicationData) data.getExtras().get("com.ShowMe.Model.PoiList");
			applicationData.getFilterPreferences();
		}
		else if(requestCode == 2){
			applicationData = (ApplicationData) data.getExtras().get("com.ShowMe.Model.PoiList");
		}
		else{
			Log.e("onActivityResult", "onActivityResult");
		}
	}
	
	
	
	private boolean isLocationAvailable(){
		String context = Context.LOCATION_SERVICE;
		LocationManager locationManager = (LocationManager)getSystemService(context);
		Criteria criteria = new Criteria();
	    criteria.setAccuracy(Criteria.ACCURACY_FINE);
	    criteria.setAltitudeRequired(false);
	    criteria.setBearingRequired(false);
	    criteria.setCostAllowed(true);
	    criteria.setPowerRequirement(Criteria.POWER_LOW );
	    String provider = locationManager.getBestProvider(criteria, true);
	    
	    if (provider != null && locationManager.isProviderEnabled(provider)) {
            // Provider is enabled
            return true;
        } else {
        	
        	//Create the location dialog
        	AlertDialog.Builder builderRestore = new AlertDialog.Builder(this);
        	//Set the location of the dialog
        	builderRestore.setMessage(R.string.msgLocation)
		       .setCancelable(false)
		       .setPositiveButton(R.string.msgYes, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   Intent settingsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//		       		settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		       		startActivityForResult(settingsIntent,3);
		       		dialog.cancel();
		       		
		           }
		       })
		       .setNegativeButton(R.string.msgLocationNo, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		                
		           }
		       });
		
			//Create and show the dialog
			builderRestore.create();
			builderRestore.show();
        	
    		
        }
	    return false;
	}
	
	private void setWindowOptions(){
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
    }
}